package com.hmall.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class GatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        // 创建一个新的ServerHttpRequest实例，包含原有请求的所有信息，并添加新的请求头
        ServerHttpRequest mutatedRequest = request.mutate()
                .header("authorization", "2") // 添加自定义请求头
                .build();

        // 用修改后的请求替换原有的请求
        ServerWebExchange newExchange = exchange.mutate().request(mutatedRequest).build();

        // 继续执行过滤器链
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        // 设置全局过滤器的执行顺序，可以根据需要调整此值
        return -1; // 值越小，优先级越高
    }
}

